<?php
uses('L10n');
class AppController extends Controller {
    public $components     = array('Cookie', 'FirePHP', 'RequestHandler');
    public $helpers        = array('Html', 'Javascript');
    public $stylesheet     = array(
        'cake.generic', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/themes/smoothness/jquery-ui.css',
        'ui.jqgrid', 'flexigrid/flexigrid', 'validationEngine.jquery', 'autocomplete',
        'linkselect/jquery.linkselect', 'spinbox/jquery.spinbox'
    );
    public $javascripts    = array(
        'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
        'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js',
        'jqGrid/grid.locale-en', 'jqGrid/jquery.jqGrid.min', 'flexigrid.min',
        'jquery.validationEngine-en', 'jquery.validationEngine', 'autocomplete.min',
        'jquery.linkselect.min', 'jquery.scrollTo-min', 'jquery.spinbox', 'common', 'phpjs'
    );
    public $firePHP        = false;
    public $allowedActions = 'all'; // Provides access for actions which most often do not require any access control.
    public $loginRedirect  = '/members/home'; // where to go after a successful login?
	public $ext            = '.html';
    public $serverTimezone = 'Asia/Kuala_Lumpur'; // 'GMT'
    public $clientTimezone = 'Asia/Kuala_Lumpur';
    public $sendmailFrom   = 'noreply@localhost';
    public $scaffold;

    public function beforeFilter () {
        //$this->loadSettings();
        Configure::write('site.sitename', 'Tang Dynasty Hotel');

        date_default_timezone_set($this->serverTimezone);
        define('SERVER_TIMEZONE', $this->serverTimezone);
        define('CLIENT_TIMEZONE', $this->clientTimezone);
        define('CLIENT_TIMEZONE_OFFSET',  timezone_offset_get(timezone_open($this->clientTimezone), date_create()));

        if ($this->RequestHandler->isAjax()) { // request contains the X-Requested-Header equal to XMLHttpRequest
            if (!class_exists('FirePHP')) { // change the debug level to 0 for all Ajax requests without FirePHP Server Lib included
                Configure::write('debug', 0);
            } else {
                Configure::write('debug', 2);
                $this->firePHP = true;
                //$this->debugMsg('It is an AJAX request and FirePHP Server Lib included. @ ['.__FILE__.']', 'info');
            }
            $m = $this->RequestHandler->getReferrer();
        }

        if ($lang = $this->Cookie->read('User.language')) { // user language
            $this->L10n = new L10n();
            $this->L10n->get('zh');
        }

        $role = $this->Session->read('Admin.logged'); //Auth.User.role
        if (substr($this->params['action'], 0, 6) == 'admin_') { // is in admin panel?
            $this->layout     = 'admin';
            $this->stylesheet = am($this->stylesheet, 'admin');

            if (!$role && $this->params['action'] != 'admin_login') { // not logged yet
                if ($this->RequestHandler->isAjax()) {
                    $this->params['action'] = 'admin_ajax_login';
                } else {
                    $this->redirect('/admin/members/login');
                }
            } else if ($role != 'admin') { // not administrator
                //__('Invalid access!',true);
            }
        } else {
            $this->stylesheet = am($this->stylesheet, 'common');
        }
    } // beforeFilter

    public function beforeRender () {
        $jscripts = is_array($this->javascripts) ? $this->javascripts : array($this->javascripts);

        if (isset($this->params['prefix']) && $this->params['prefix'] == 'rest') {
            $rest = true;
        }

        if ($this->layout == 'default' && empty($rest)) {
            $this->loadModel('RoomType');
            $roomTypes = $this->RoomType->find('all', array(
                'recursive' => -1,
                'fields'    => array('id', 'code', 'description'),
                'order'     => 'id ASC'
            ));

            $this->loadModel('RateCode');
            $rateCodes = $this->RateCode->find('all', array(
                'recursive' => -1,
                'fields'    => array('id', 'code', 'description'),
                'order'     => 'code ASC'
            ));

            $this->loadModel('Rate');
            $data = $this->Rate->find('all', array(
                'recursive' => -1,
                'fields'    => array('id', 'room_type_id', 'rate_code_id', 'from', 'to', 'description', 'd_1', 'd_2', 'd_3', 'd_4', 'e_1', 'e_2', 'e_3', 'e_4'),
                'order'     => array('room_type_id')
            ));
            $rates = array();

            foreach ($data as $i=>$r) {
                $rates[$i]              = $r['Rate'];
                $rates[$i]['rate_code'] = '';

                foreach ($roomTypes as $t) {
                    if ($t['RoomType']['id'] == $r['Rate']['room_type_id']) {
                        $rates[$i]['room_type_code'] = $t['RoomType']['code'];
                    }
                }
                foreach ($rateCodes as $c) {
                    if ($c['RateCode']['id'] == $r['Rate']['rate_code_id']) {
                        $rates[$i]['rate_code'] = $c['RateCode']['code'];
                    }
                }

                $rates[$i]['from_time'] = strtotime($r['Rate']['from']);
                $rates[$i]['to_time']   = strtotime($r['Rate']['to']);
            }

            $this->set('roomTypes', $roomTypes);
            $this->set('rateCodes', $rateCodes);
            $this->set('rates', $rates);
        }

        $this->set('stylesheet', $this->stylesheet);
        $this->set('javascripts', $jscripts);
        $this->set('sitename', Configure::read('site.sitename'));
        $this->set('user_id', $this->Session->read('User.id'));
    } // beforeRender

    public function checkAuth () {
        if (isset($this->Auth)) {
            $this->Auth->autoRedirect = false;
            $this->Auth->mapActions(array('display'=>'read'));

            // tell Auth which actions do not need any access control
            if (isset($this->allowedActions)) { // shared between all application's controllers
               $this->Auth->allow($this->allowedActions);
            }
            if (isset($this->publicActions)) { // use in controller extended AppController
               $this->Auth->allow($this->publicActions);
            }

            $this->Auth->fields        = array('username'=>'email', 'password'=>'password');
            $this->Auth->userScope     = array('Member.status'=>'A');
            $this->Auth->loginAction   = '/members/login';
            $this->Auth->loginRedirect = $this->loginRedirect;
            //$this->Auth->authorize = 'controller';
            $this->Auth->loginError    = '<h4>'.__('Sorry, login failed. Either your username or password are incorrect.', true).'</h4>';
            $this->Auth->authError     = '<h4>'.__('The page you tried to access is restricted. You have been redirected to the page below.', true).'</h4>';
        }
    } // checkAuth

    public function loadSettings () {
        App::import('Model', 'Setting');
        $o_setting = new Setting();

        $params = array(
            'fields' => 'Setting.category, Setting.short_name, Setting.value',
            'order'  => 'Setting.category ASC, Setting.position ASC'
        );
        $settings = $o_setting->find('all', $params);

        foreach ($settings as $data) {
            $key   = $data['Setting']['category'].'.'.$data['Setting']['short_name'];
            $value = $data['Setting']['value'];
            Configure::write($key, $value);
        }
    } // loadSettings

    public function clientToServerTime ($datetime, $format='Y-m-d H:i:s') {
        date_default_timezone_set($this->clientTimezone); // switch to client timezone first

        $datetimeObject = date_create($datetime); // create datetime object
        $serverTimezone = timezone_open($this->serverTimezone); // create server timezone object

        date_timezone_set($datetimeObject, $serverTimezone); // switch datetime object follow server timezone

        return date_format($datetimeObject, $format);
    } // clientToServerTime

    public function serverToClientTime ($datetime, $format='Y-m-d H:i:s') {
        date_default_timezone_set($this->serverTimezone); // switch to server timezone first

        $datetimeObject = date_create($datetime); // create datetime object
        $clientTimezone = timezone_open($this->clientTimezone); // create client timezone object

        date_timezone_set($datetimeObject, $clientTimezone); // switch datetime object follow client timezone

        return date_format($datetimeObject, $format);
    } // serverToClientTime

    public function response ($json) {
        $this->set('json', $json);
        $this->render(false, 'json');
    } // response

    public function rest_input ($ext) {
        $get = array();

        if (count($this->params['url']) > 0) {
            foreach ($this->params['url'] as $k=>$v) {
                if ($k != 'ext' && $k != 'url') {
                    $get[$k] = $v;
                }
            }
        }

        if (count($get) > 0) {
            $params = $this->params['url'];
        } else if (count($this->params['form']) > 0) {
            $params = $this->params['form'];
        }

        if (empty($params)) {
            $this->rest_render($ext, array(
                'response' => array(
                    'status'  => -1,
                    'message' => __('No data found.', true)
                )
            ));
            return false;
        }

        return $params;
    } // rest_input

    public function rest_render ($format, $data) {
        Configure::write('debug', 0);

        if ($format == 'xml') {
            $content_type  = 'text/xml';
            $this->helpers = am($this->helpers, 'xml');
            $this->set('name', $this->params['controller']);
            $this->set('data', $data);
        } else if ($format == 'json') {
            $content_type = 'application/javascript';
            $this->set('json', $data);
        } else if ($format == 'txt') {
            $content_type = 'text/plain';
            $this->set('data', $data);
        }

        header('Content-Type: '.$content_type);
        $this->render(false, $format);
    } // rest_render

    public function debugMsg ($message, $type='') {
        if (!class_exists('FirePHP')) {
            return false;
        }

        switch ($type) {
           case 'error':
             $this->FirePHP->error($message);
             break;

           case 'warn':
             $this->FirePHP->warn($message);
             break;

           case 'info':
           default:
             $this->FirePHP->info($message);
             break;
        }
    } // debugMsg

    public function _checkLogged () {
        $logged = $this->Session->read('Member.logged');

        if ($logged) {
            return true;
        }
        if ($this->RequestHandler->isAjax()) {
            $json = array(
                'status' => -2
            );
            $this->response($json);
            return false;
        }

        $this->redirect('/members/login');
    } // _checkLogged
} // AppController
